import Api from '@/api.js'

export default {
  data: function () {
    return {
      userInfo: null,
      request: new function () {
        let name, value
        let str = location.href
        let num = str.indexOf('?')
        str = str.substr(num + 1)
        let arr = str.split('&')
        for (let i = 0; i < arr.length; i++) {
          num = arr[i].indexOf('=')
          if (num > 0) {
            name = arr[i].substring(0, num)
            value = arr[i].substr(num + 1)
            this[name] = value
          }
        }
      }
    }
  },
  methods: {
    checkWebpFeature: function (feature, callback) {
      let kTestImages = {
        lossy: "UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA",
        lossless: "UklGRhoAAABXRUJQVlA4TA0AAAAvAAAAEAcQERGIiP4HAA==",
        alpha: "UklGRkoAAABXRUJQVlA4WAoAAAAQAAAAAAAAAAAAQUxQSAwAAAARBxAR/Q9ERP8DAABWUDggGAAAABQBAJ0BKgEAAQAAAP4AAA3AAP7mtQAAAA==",
        animation: "UklGRlIAAABXRUJQVlA4WAoAAAASAAAAAAAAAAAAQU5JTQYAAAD/////AABBTk1GJgAAAAAAAAAAAAAAAAAAAGQAAABWUDhMDQAAAC8AAAAQBxAREYiI/gcA"
      }
      let img = new Image()
      img.onload = function () {
        let result = (img.width > 0) && (img.height > 0)
        callback(feature, result)
      }
      img.onerror = function () {
        callback(feature, false)
      }
      img.src = "data:image/webp;base64," + kTestImages[feature]
    },
    setMinHeight: function (dom, minHeight) {
      dom.style.minHeight = `${minHeight}px`
    },
    login: function () {
      Api.user.login({"t": "1"}).then(res => {
        window.location.href = res.data.authorizeCodeUrl
      }, err => {
        console.log(err)
        alert('Error')
      })
    },
    jump(to) {
      if (this.$router) {
        this.$router.push(to)
      }
    },
    getLoginState: function () {
      localStorage.urlCallback = location.href
      let getData = function (key) {
        return localStorage.getItem(key)
      }
      let isLogin = localStorage && getData('userName') && getData('userDbId')
      if (isLogin) {
        this.userInfo = {
          userDbId: getData('userDbId'),
          userName: getData('userName'),
          avatar: getData('avatar')
        }
      }
      return isLogin
    },
    convertParams: function (params) {
      if (!params) {
        return
      }
      let array = []
      for (let key in params) {
        array.push(`${key}=${params[key]}`)
      }
      return array.join('&')
    },
    dynamicAlterUrl: function (params) {
      if (!params) {
        return
      }
      let uri = [location.protocol, '//', location.host, location.pathname].join('')
      let url = uri + '?' + this.convertParams(params)
      if (history.pushState) {
        history.pushState({}, document.title, url)
        return
      }
      window.location.href = url
    }
  },
  components: {},
  watch: {},
  created: function () {
  }
}
